package com.masterclient.app.modules.purchase.widget;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.eoner.baselibrary.bean.goods.ChildProductMessage;
import com.eoner.baselibrary.bean.goods.CommodityAttribute;
import com.eoner.baselibrary.bean.goods.ProductSpecificationData;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.masterclient.app.R;
import com.masterclient.app.modules.purchase.adapter.PurchaseAttributesAdapter;
import com.masterclient.app.modules.purchase.adapter.PurchaseAttributesPriceAdapter;
import com.masterclient.app.widget.KeyboardStatusDetector;

import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

/**
 * @auther hjian
 * @date 2020/9/17.
 */
public class PurchaseSkuDialog extends Dialog {


    @BindView(R.id.dialog_purchase_sku_price)
    TextView dialogPurchaseSkuPrice;
    @BindView(R.id.dialog_purchase_sku_close)
    FrameLayout dialogPurchaseSkuClose;
    @BindView(R.id.dialog_purchase_sku_attributes)
    TextView dialogPurchaseSkuAttributes;
    @BindView(R.id.dialog_purchase_sku_head)
    FrameLayout dialogPurchaseSkuHead;
    @BindView(R.id.dialog_purchase_sku_recycler)
    RecyclerView dialogPurchaseSkuRecycler;
    @BindView(R.id.dialog_purchase_sku_reduce)
    ImageView dialogPurchaseSkuReduce;
    @BindView(R.id.dialog_purchase_sku_num)
    EditText dialogPurchaseSkuNum;
    @BindView(R.id.dialog_purchase_sku_plus)
    ImageView dialogPurchaseSkuPlus;
    @BindView(R.id.dialog_purchase_sku_hint)
    TextView dialogPurchaseSkuHint;
    @BindView(R.id.dialog_purchase_sku_hint_layout)
    LinearLayout dialogPurchaseSkuHintLayout;
    @BindView(R.id.dialog_purchase_sku_total)
    TextView dialogPurchaseSkuTotal;
    @BindView(R.id.dialog_purchase_sku_recycler_price)
    RecyclerView dialogPurchaseSkuRecyclerPrice;
    @BindView(R.id.dialog_purchase_sku_cart)
    TextView dialogPurchaseSkuCart;
    @BindView(R.id.dialog_purchase_sku_buy)
    TextView dialogPurchaseSkuBuy;
    @BindView(R.id.dialog_purchase_sku_bottom)
    FrameLayout dialogPurchaseSkuBottom;
    @BindView(R.id.dialog_purchase_sku_img)
    ImageView dialogPurchaseSkuImg;
    @BindView(R.id.dialog_purchase_sku_price_desc_layout)
    FrameLayout dialogPurchaseSkuPriceDescLayout;
    @BindView(R.id.dialog_purchase_sku_price_desc)
    TextView dialogPurchaseSkuPriceDesc;

    private Activity mContext;
    private PurchaseAttributesAdapter attributesAdapter;
    private long productNum = 1;
    private ProductSpecificationData specificationData;
    private String attributeNotStr;
    private int attributeSize;
    private String childProductId = "";

    public PurchaseSkuDialog(@NonNull Activity context,ProductSpecificationData specificationData,SkuClickListener skuClickListener) {
        super(context, R.style.MyDialog);
        mContext = context;
        this.specificationData = specificationData;
        this.skuClickListener = skuClickListener;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_purchase_sku);
        ButterKnife.bind(this);
        setCanceledOnTouchOutside(true);
        attributeSize = specificationData.getAttributes().size();

        Utils.setDin(dialogPurchaseSkuPrice,mContext);
        Utils.set_price_style(dialogPurchaseSkuPrice,new StringBuffer("¥ ").append(specificationData.getPrice()).toString(),0.48f);
        ViewTransformUtil.glideImageView(mContext, specificationData.getImage(), dialogPurchaseSkuImg, new Transformation[]{new CenterCrop(),
                new RoundedCornersTransformation(ScreenUtils.dp2px(7), 0)}, R.mipmap.defaults);
        dialogPurchaseSkuTotal.setText(specificationData.getGrand_total_num());
        if (!TextUtils.isEmpty(specificationData.getSale_tip_text())){
            dialogPurchaseSkuHintLayout.setVisibility(View.VISIBLE);
            dialogPurchaseSkuHint.setText(specificationData.getSale_tip_text());
        }else {
            dialogPurchaseSkuHintLayout.setVisibility(View.GONE);
        }

        //未选择的规格显示
        StringBuffer attributeBuffer = new StringBuffer();
        attributeBuffer.append("请选择: ");
        for (CommodityAttribute attribute : specificationData.getAttributes()) {
            attributeBuffer.append(attribute.getLabel()).append("-");
        }
        attributeNotStr = attributeBuffer.substring(0,attributeBuffer.toString().length()-1);
        dialogPurchaseSkuAttributes.setText(attributeNotStr);

        //规格列表
        attributesAdapter = new PurchaseAttributesAdapter();
        dialogPurchaseSkuRecycler.setLayoutManager(new LinearLayoutManager(mContext));
        attributesAdapter.bindToRecyclerView(dialogPurchaseSkuRecycler);
        attributesAdapter.setNewData(specificationData.getAttributes());

        //拿货量对应价格
        dialogPurchaseSkuRecyclerPrice.setLayoutManager(new LinearLayoutManager(mContext));
        PurchaseAttributesPriceAdapter priceAdapter = new PurchaseAttributesPriceAdapter();
        priceAdapter.bindToRecyclerView(dialogPurchaseSkuRecyclerPrice);
        priceAdapter.setNewData(specificationData.getStep_prices());
        if (!TextUtils.isEmpty(specificationData.getMore_step_price_text())){
            dialogPurchaseSkuPriceDescLayout.setVisibility(View.VISIBLE);
            dialogPurchaseSkuPriceDesc.setText(specificationData.getMore_step_price_text());
        }else {
            dialogPurchaseSkuPriceDescLayout.setVisibility(View.GONE);
        }

        initeListener();
        dialogPurchaseSkuReduce.setImageResource(productNum <= 1 ? R.mipmap.icon_purchase_grey_sub : R.mipmap.icon_purchase_sub);
    }

    private void initeListener() {

        attributesAdapter.setOnAttrItemClickListener(new PurchaseAttributesAdapter.OnAttrItemClickListener() {
            @Override
            public void onAttrItemClick(List<Set<Integer>> list) {
                attributeSelect(list);
            }
        });

        dialogPurchaseSkuNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String content = dialogPurchaseSkuNum.getText().toString();
                if (TextUtils.isEmpty(content)){
                    productNum = 1;
                }else {
                    if (Long.parseLong(content) == 0){
                        dialogPurchaseSkuNum.setText("1");
                        dialogPurchaseSkuNum.setSelection(1);
                        return;
                    }
                    productNum = Long.parseLong(content);
                }

                dialogPurchaseSkuReduce.setImageResource(productNum <= 1 ? R.mipmap.icon_purchase_grey_sub : R.mipmap.icon_purchase_sub);

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        new KeyboardStatusDetector().registerActivity(mContext).setmVisibilityListener(new KeyboardStatusDetector.KeyboardVisibilityListener() {
            @Override
            public void onVisibilityChanged(boolean keyboardVisible) {
                if (!keyboardVisible) {
                    if (TextUtils.isEmpty(dialogPurchaseSkuNum.getText().toString().trim())) {
                        dialogPurchaseSkuNum.setText("1");
                        dialogPurchaseSkuNum.setSelection(1);
                    }
                }
            }
        });
    }

    /**
     * 点击规格处理
     * @param list
     */
    private void attributeSelect(List<Set<Integer>> list){

        childProductId = "";
        int selectedSize = 0;
        StringBuffer selectedCode = new StringBuffer();
        StringBuffer attributeBuffer = new StringBuffer("已选择: ");

            for (int i = 0; i < list.size(); i++) {
                for (Integer sets : list.get(i)) {
                    ++selectedSize;
                    selectedCode.append(specificationData.getAttributes().get(i).getOptions().get(sets).getOption_id());
                    attributeBuffer.append(specificationData.getAttributes().get(i).getOptions().get(sets).getTitle());
                    attributeBuffer.append("；");
                    selectedCode.append("_");
                }
            }
            if (selectedSize>0){
                attributeBuffer.deleteCharAt(attributeBuffer.toString().length()-1);
                selectedCode.deleteCharAt(selectedCode.toString().length()-1);
            }

            if (selectedSize == attributeSize){
                for (ChildProductMessage message : specificationData.getChild_products()) {
                    if (message.getSku_code().equals(selectedCode.toString())){
                        childProductId = message.getProduct_id();
                        Utils.set_price_style(dialogPurchaseSkuPrice,new StringBuffer("¥ ").append(message.getPrice()).toString(),0.48f);
                        ViewTransformUtil.glideImageView(mContext, message.getImage(), dialogPurchaseSkuImg, new Transformation[]{new CenterCrop(),
                                new RoundedCornersTransformation(ScreenUtils.dp2px(7), 0)}, R.mipmap.defaults);
                        break;
                    }
                }
            }else {
                Utils.set_price_style(dialogPurchaseSkuPrice,new StringBuffer("¥ ").append(specificationData.getPrice()).toString(),0.48f);
                ViewTransformUtil.glideImageView(mContext, specificationData.getImage(), dialogPurchaseSkuImg, new Transformation[]{new CenterCrop(),
                        new RoundedCornersTransformation(ScreenUtils.dp2px(7), 0)}, R.mipmap.defaults);
            }
        dialogPurchaseSkuAttributes.setText(selectedSize>0?attributeBuffer.toString():attributeNotStr);
//        }else {
//            Utils.set_price_style(dialogPurchaseSkuPrice,new StringBuffer("¥ ").append(specificationData.getPrice()).toString(),0.48f);
//            ViewTransformUtil.glideImageView(mContext, specificationData.getImage(), dialogPurchaseSkuImg, new Transformation[]{new CenterCrop(),
//                    new RoundedCornersTransformation(ScreenUtils.dp2px(7), 0)}, R.mipmap.defaults);
//            dialogPurchaseSkuAttributes.setText(attributeNotStr);
//        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        Window window = getWindow();
        window.setWindowAnimations(R.style.bottomShow);
        WindowManager.LayoutParams windowparams = window.getAttributes();
        window.setGravity(Gravity.BOTTOM);
        windowparams.width = ScreenUtils.getScreenWidth();
        windowparams.height = ScreenUtils.getScreenHeight() * 5 / 6;
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.setAttributes(windowparams);
    }

    @OnClick({R.id.dialog_purchase_sku_close, R.id.view_purchase_sku_reduce, R.id.view_purchase_sku_plus, R.id.dialog_purchase_sku_cart, R.id.dialog_purchase_sku_buy, R.id.dialog_purchase_sku_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.dialog_purchase_sku_close:
                dismiss();
                break;
            case R.id.view_purchase_sku_reduce:
                setNum(productNum - 1);
                break;
            case R.id.view_purchase_sku_plus:
                setNum(productNum + 1);
                break;
            case R.id.dialog_purchase_sku_cart:
                if (TextUtils.isEmpty(childProductId)){
                    ToastUtil.showToast("请选择商品属性");
                    return;
                }
                skuClickListener.onSkuClick(this,0, childProductId, String.valueOf(productNum));
                break;
            case R.id.dialog_purchase_sku_buy:
                if (TextUtils.isEmpty(childProductId)){
                    ToastUtil.showToast("请选择商品属性");
                    return;
                }
                skuClickListener.onSkuClick(this,1, childProductId, String.valueOf(productNum));
                break;
            case R.id.dialog_purchase_sku_img:
                break;
        }
    }

    private void setNum(long num) {
        if (num < 1) num = 1;
        productNum = num;
        dialogPurchaseSkuReduce.setImageResource(productNum <= 1 ? R.mipmap.icon_purchase_grey_sub : R.mipmap.icon_purchase_sub);
        dialogPurchaseSkuNum.setText(String.valueOf(num));
        dialogPurchaseSkuNum.setSelection(String.valueOf(num).length());
    }

    private SkuClickListener skuClickListener;
    public interface SkuClickListener{
        void onSkuClick(PurchaseSkuDialog dialog, int type, String product_id, String num);
    }
}
